<script setup>
import { ref, reactive, watch, onMounted, h } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { devicegroupApi, deviceApi as MainApi, deviceById as MainById, devicegroupkeyApi, devicegroupkeyvalueApi } from '@T2/service/api.ts';
import { distributeAIntoB } from '@T2/utils/utils.ts';
import { useIuserInfoStore } from '@T2/store/users.ts';
import AddEditDevice from './component/addEditDevice.vue';
import WarnSet from '../components/warnSet.vue';

const iuserInfoStore = useIuserInfoStore();
const { getHandleRight } = iuserInfoStore;
const RIGHT = getHandleRight(['371', '372', '373', '374', '375']);

const props = defineProps({
  unit: {
    type: Object,
    required: true,
  },
  update: {
    type: Number,
    default: 0,
  }
});
const emits = defineEmits(['pagesChange']);

onMounted(() => {
  getDeviceGroupList();
});

const Resd = reactive({
  tab: 0,
});

/* 设备组切换 */
watch(() => props.update, (nv, ov) => {
  MainTable.editRow = null;
  getDeviceGroupList();
});
watch(() => props.unit.id, (nv, ov) => {
  Resd.tab = 0;
  if (nv) {
    MainTable.editRow = null;
    getDeviceGroupList();
  }
});
watch(() => Resd.tab, (nv, ov) => {
  MainTable.editRow = null;
  getKeyAndValues();
  GetMainTable();
});
const devicegroups = ref([]);
const getDeviceGroupList = () => {
  devicegroups.value = [];
  devicegroupApi({
    method: 'get',
    params: {
      page: 1,
      ordering: 'index',
      unit: props.unit.id,
    }
  }).then(res => {
    devicegroups.value = res?.results || [];
    GetMainTable();
  });
}

const devicegroupkeys = ref([]);
const getKeyAndValues = () => {
  devicegroupkeys.value = [];
  if (!Resd.tab) {
    return;
  }
  
  Promise.all([getDevicegroupkey(), getDevicegroupkeyvalues()]).then(res => {
    let arr0 = res[0], arr1 = res[1];
    const { updatedB } = distributeAIntoB(arr1, arr0, 'devicegroupkey');
    devicegroupkeys.value = updatedB;
  });
}

const getDevicegroupkey = () => {
  return new Promise((resolve, reject) => {
    devicegroupkeyApi({
      method: 'get',
      params: {
        devicegroup: Resd.tab || null,
        ordering: 'index',
      }
    }).then(res => {
      resolve(res?.results || []);
    }).catch(err => {
      reject(err);
    });
  });
  
}

const getDevicegroupkeyvalues = () => {
  return new Promise((resolve, reject) => {
    devicegroupkeyvalueApi({
      method: 'get',
      params: {
        devicegroup: Resd.tab,
      }
    }).then(res => {
      resolve(res?.results || []);
    }).catch(err => {
      reject(err);
    });
  });
}

const MainTable = reactive({
  data: [],
  total: 0,
  editRow: null,
});
const Filter = reactive({
  page: 1,
  pagesize: 30,
  search: '',
});
watch(() => ({...Filter}), (nv, ov) => {
  if (nv.page === 1 || nv.page !== ov.page) {
    GetMainTable();
  } else {
    Filter.page = 1;
  }
});
const GetMainTable = () => {
  MainTable.data = [];
  if (!props.unit.id) {
    return;
  }
  MainApi({
    method: 'get',
    params: {
      ...Filter,
      pagesize: Resd.tab ? Filter.pagesize : null,
      ordering: '-create_time',
      devicegroup: Resd.tab || null,
      unit: props.unit?.id,
      front_delete: false,
    }
  }).then(res => {
    MainTable.data = res?.results || [];
    MainTable.total = res?.count || 0;
    if (!Resd.tab) {
      MainTable.data = MainTable.data.filter(i => !i.devicegroup);
      if (!MainTable.data.length && devicegroups.value.length) {
        Resd.tab = devicegroups.value[0].id;
      }
    }
  });
}
const handleMainDelete = (isAble = false, row) => {
  if (!isAble) {
    return;
  }
  ElMessageBox.confirm('', {
    message: h('div', null,[
      h('p',{ style:'font-size:16px;color: #4C4C4C;font-weight:500;'}, `您是否要删除 ${ row.name }？`),
    ]),
    type: 'warning',
    confirmButtonText: '确认',
  }).then(() => {
    MainById({
      method: 'patch',
      id: row.id,
      data: {
        front_delete: true,
      }
    }).then(res => {
      ElMessage.success('删除成功');
      GetMainTable();
    });
  }).catch(() => {
    ElMessage.info('已取消');
  });
}

/* 新增编辑 */
const MainPopup = reactive({
  type: '',
  info: {
    unit: null,
    devicegroup: null,
    devicegroup_name: '',
  },
  devicegroupkeys: [],
  device: null,
});
const changeMainPopupType = (isAble = false, type, row = null) => {
  if (!isAble) {
    return;
  }
  MainPopup.type = type;
  MainPopup.device = row;
  MainPopup.info.unit = props.unit.id;
  MainPopup.info.devicegroup = Resd.tab;
  MainPopup.info.devicegroup_name = devicegroups.value.find(i => i.id === Resd.tab)?.name;
  MainPopup.devicegroupkeys = devicegroupkeys.value.map(i => {
    let arr = i.children?.filter(j => j.device === row?.id);
    return { ...i, children: arr }
  });
}
const devicegroupMainChange = (row) => {
  MainTable.editRow = null;
  MainById({
    method: 'patch',
    id: row.id,
    data: {
      devicegroup: row.devicegroup,
    }
  }).then(res => {
    ElMessage.success('更改组别成功！');
    GetMainTable();
  });
}
const formattetDevicegroup = (id) => {
  return devicegroups.value.find(i => i.id === id)?.name || '';
}

const goToDevicegroup = (isAble = false) => {
  if (!isAble) {
    return;
  }
  emits('pagesChange', 'devicegroup');
}

/* 报警配置 */
const warnSetInfo = ref(null);
const warnPopupSet = (isAble = false, row) => {
  if (!isAble) {
    return;
  }
  warnSetInfo.value = row;
}
</script>

<template>
  <div class="deviceList-box flex-column mainCard">
    <div class="devicegroup-lines flex--center">
      <el-tabs v-model="Resd.tab" class="demo-tabs">
        <el-tab-pane :label="item.name" :name="item.id" v-for="item in devicegroups"></el-tab-pane>
        <el-tab-pane label="未分组设备" :name="0"></el-tab-pane>
      </el-tabs>
      <div class="right-btns">
        <el-button style="color: #1890FF; border-color: #1890FF;" @click="goToDevicegroup(RIGHT['375'])" :disabled="!RIGHT['375']">
          管理设备组
        </el-button>
        <template v-if="Resd.tab">
          <el-button type="primary"  @click="changeMainPopupType(RIGHT['371'], '新增')" :disabled="!RIGHT['371']">
            新增
          </el-button>
        </template>
      </div>
    </div>
    
    <el-table :data="MainTable.data" scrollbar-always-on>
      <el-table-column label="设备名称" prop="name" min-width="160px"></el-table-column>
      <el-table-column label="设备位号" prop="code" min-width="120px"></el-table-column>
      <el-table-column label="组别" prop="devicegroup" min-width="140px">
        <template #default="scope">
          <el-select v-model="scope.row.devicegroup" style="width: 122px;" v-if="MainTable.editRow === scope.$index">
            <el-option
              :value="item.id"
              :label="item.name"
              v-for="item in devicegroups"
            />
          </el-select>
          <span v-else>{{ formattetDevicegroup(scope.row.devicegroup) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-for="item in devicegroupkeys.slice(0, 8)"
        :label="item.name"
        width="auto"
        min-width="120px"
        show-overflow-tooltip
      >
        <template #default="scope">
          <div class="flex-column">
            <span v-for="keyvalue in (item.children?.filter(i => i.device === scope.row.id) || [])">{{ keyvalue.value }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" :width="Resd.tab ? '300px' : '240px'">
        <template #default="scope">
          <template v-if="MainTable.editRow === scope.$index">
            <el-button link type="primary" @click="devicegroupMainChange(scope.row)">保存</el-button>
            <el-button link type="primary" @click="MainTable.editRow = null">取消</el-button>
          </template>
          <template v-else-if="MainTable.editRow === null">
            <el-button link type="primary" @click="warnPopupSet(RIGHT['374'], scope.row)" :disabled="!RIGHT['374']">
              告警配置
            </el-button>
            <el-button link type="primary" @click="MainTable.editRow = scope.$index" :disabled="!devicegroups.length">
              修改组别
            </el-button>
            <template v-if="Resd.tab">
              <el-button link type="primary" @click="changeMainPopupType('详情', scope.row)">
                详情
              </el-button>
              <el-button link type="primary" @click="changeMainPopupType(RIGHT['372'], '编辑', scope.row)" :disabled="!RIGHT['372']">
                编辑
              </el-button>
            </template>
            <el-button link type="danger" @click="handleMainDelete(RIGHT['373'], scope.row)" :disabled="!RIGHT['373']">
              删除
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-if="Resd.tab"
      layout="->, total, prev, pager, next, sizes"
      background 
      :page-sizes="[10, 20, 30, 50, 100]"
      :pager-count="5"
      v-model:currentPage="Filter.page"
      v-model:page-size="Filter.pagesize"
      :total="MainTable.total"
    />
  </div>
  
  <AddEditDevice
    v-if="MainPopup.type"
    :type="MainPopup.type"
    :devicegroupkeys="MainPopup.devicegroupkeys"
    :info="MainPopup.info"
    :device="MainPopup.device"
    @closed="changeMainPopupType('')"
    @refresh="GetMainTable();getKeyAndValues();"
  />
  
  <WarnSet
    :device="warnSetInfo"
    @closed="warnSetInfo = null"
  />
</template>

<style lang="scss" scoped>
@use '@T2/styles/normal.scss';
.view {
  width: 100%;
  height: 100%;
}
.deviceList-box {
  flex: 1;
  overflow: hidden;
  position: relative;
}
.devicegroup-lines {
  width: 100%;
  margin-bottom: 24px;
  .demo-tabs {
    // flex: 1;
  }
  .right-btns {
    margin-left: auto;
  }
}
</style>

<style scoped>
:deep(.demo-tabs .el-tabs__header) {
  margin: 0;
}
:deep(.demo-tabs .el-tabs__nav-wrap::after) {
  background-color: transparent;
}
</style>